package com.xuecheng.content.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.basic.api.BasicClient;
import com.xuecheng.commons.constants.CourseConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.vo.CategoryVo;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.model.vo.TeachplanVo;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.content.domain.CourseBase;
import com.xuecheng.content.domain.CoursePub;
import com.xuecheng.content.mappers.CoursePubMapper;
import com.xuecheng.content.service.CourseBaseService;
import com.xuecheng.content.service.CoursePubService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.content.service.TeachplanService;
import com.xuecheng.web.exceptions.BusinessException;
import freemarker.template.TemplateException;
import io.minio.errors.*;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 课程发布 服务实现类
 * </p>
 *
 * @author 七安
 * @since 2022-09-17
 */
@Service
public class CoursePubServiceImpl extends ServiceImpl<CoursePubMapper, CoursePub> implements CoursePubService {

    @Autowired
    private BasicClient basicClient;

    @Autowired
    private CoursePubMapper coursePubMapper;

    @Autowired
    private CourseBaseService courseBaseService;

    @Autowired
    private TeachplanService teachplanService;

    @Autowired
    private UploadHtml uploadHtml;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 课程发布预览
     *
     * @param courseBaseId id
     * @return 结果
     */
    @Override
    public Map<String, Object> releasePreview(Long courseBaseId) throws BusinessException {
        //根据id查询课程
        CourseBase courseBase = courseBaseService.getById(courseBaseId);
        //判空
        if (ObjectUtils.isEmpty(courseBase)) {
            throw new BusinessException(ErrorCode.DATAERROR);
        }
        //查询课程计划
        TeachplanVo teachplanVo = teachplanService.findTeachplanByCourseId(courseBaseId);
        //todo 查询教师信息
        //复制Bean
        CoursePub coursePub = BeanHelper.copyProperties(courseBase, CoursePub.class);
        //id重置
        coursePub.setId(null);
        //设置课程id
        coursePub.setCourseId(courseBase.getId());
        //设置分类名称
        //大分类
        String mtName = findSortNameById(coursePub.getMt());
        coursePub.setMtName(mtName);
        //小分类
        String stName = findSortNameById(coursePub.getSt());
        coursePub.setStName(stName);
        //设置课程计划
        coursePub.setTeachplan(JSON.toJSONString(teachplanVo));
        //todo 设置老师信息
        HashMap<String, Object> map = new HashMap<>();
        map.put("coursePub", coursePub);
        map.put("teachplanNode", teachplanVo);
        return map;
    }

    /**
     * 根据id查询分类名称
     *
     * @param id id
     * @return 名称
     * @throws BusinessException 数据未找到
     */
    public String findSortNameById(String id) throws BusinessException {
        //调用feign接口
        ResponseResult<CategoryVo> responseResult = basicClient.findSortName(id);
        //判断
        if (ErrorCode.SUCCESS.getCode() != (responseResult.getCode())) {
            throw new BusinessException(ErrorCode.DATAERROR);
        }
        return responseResult.getData().getName();
    }

    /**
     * 课程发布
     *
     * @param courseBaseId 课程id
     * @return 发布结果
     */
    @Override
    public ResponseResult coursePublish(Long courseBaseId) throws BusinessException, IOException, TemplateException, ServerException, InvalidBucketNameException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        //根据id查询课程
        CourseBase courseBase = courseBaseService.getById(courseBaseId);
        //判空和当前课程状态
        if (ObjectUtils.isEmpty(courseBase) ||
                courseBase.getAuditStatus().equals(CourseConstants.AUDIT_DISPAST_STATUS) ||
                courseBase.getAuditStatus().equals(CourseConstants.AUDIT_UNPAST_STATUS) ||
                courseBase.getAuditStatus().equals(CourseConstants.AUDIT_COMMIT_STATUS)) {
            throw new BusinessException(ErrorCode.COURSEPUBSHRRROR);
        }
        //整合课程发布对象
        Map<String, Object> map = releasePreview(courseBaseId);
        //强转
        CoursePub coursePub = (CoursePub) map.get("coursePub");
        //创建查询wrapper，查找有没有发布信息
        LambdaQueryWrapper<CoursePub> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CoursePub::getCourseId, courseBaseId);
        CoursePub pub = getOne(wrapper);
        //判空
        if (ObjectUtils.isEmpty(pub)) {
            //如果为空就新增
            save(coursePub);
        }
        if (ObjectUtils.isNotEmpty(pub)) {
            //如果不为空就修改
            coursePub.setId(pub.getId());
            updateById(coursePub);
        }
        //更新课程状态
        courseBase.setAuditStatus(CourseConstants.AUDIT_PUBLISHED_STATUS);
        courseBaseService.updateById(courseBase);
        //上传html
        uploadHtml.uploadHtml(coursePub.getId(), map);
        //向MQ发送消息
        rabbitTemplate.convertAndSend("content-exchange", "course-pub", coursePub.getId());
        return ResponseResult.okResult();
    }
}
